package com.aabte.controller;

import com.aabte.service.DeferredResultQueue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.concurrent.Callable;

@Controller
public class AsyncController {

    @ResponseBody
    @RequestMapping("/async01")
    public Callable<String> async01(){

        System.out.println("主线程开始 " + Thread.currentThread() + " " + System.currentTimeMillis());

        Callable<String> callable = new Callable<String>() {

            @Override
            public String call() throws Exception {

                System.out.println("子线程开始 " + Thread.currentThread() + " " + System.currentTimeMillis());

                Thread.sleep(2000);

                System.out.println("子线程结束 " + Thread.currentThread() + " " + System.currentTimeMillis());

                return "Callable<String> async01()";
            }
        };

        System.out.println("主线程结束 " + Thread.currentThread() + " " + System.currentTimeMillis());

        return callable;

    }

    @ResponseBody
    @RequestMapping("/createOrder")
    public DeferredResult<Object> createOrder(){

        DeferredResult<Object> deferredResult = new DeferredResult<>(3000L, "create failed.");

        DeferredResultQueue.save(deferredResult);

        return deferredResult;
    }

    @ResponseBody
    @RequestMapping("/create")
    public String create(){

        String uuid = UUID.randomUUID().toString();

        DeferredResult deferredResult = DeferredResultQueue.get();
        if (null != deferredResult) {
            deferredResult.setResult("createOrder ->" + uuid);
        }

        return "create ->" + uuid;
    }

}
